package cn.player.media.fragment;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import net.tsz.afinal.bitmap.core.BitmapDisplayConfig;
import net.tsz.afinal.bitmap.display.Displayer;
import net.tsz.afinal.bitmap.display.SimpleDisplayer;

import org.json.JSONObject;

import java.lang.ref.WeakReference;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import cn.player.R;
import cntv.player.core.util.LogUtil;
import cntv.player.core.util.SprefUtils;
import cntv.player.core.util.Utils;
import cntv.player.engine.Const;
import cntv.player.media.player.IMediaPlayer;
import cntv.player.media.player.IMediaPlayer.OnBufferingUpdateListener;
import cntv.player.media.player.IMediaPlayer.OnCompletionListener;
import cntv.player.media.player.IMediaPlayer.OnErrorListener;
import cntv.player.media.player.IMediaPlayer.OnInfoListener;
import cntv.player.media.player.IMediaPlayer.OnPreparedListener;
import cntv.player.media.player.IMediaPlayer.OnSurfaceListener;
import cntv.player.media.player.IMediaPlayer.OnVideoClickListener;
import cntv.player.media.player.IMediaPlayer.OnVideoSizeChangedListener;
import cntv.player.media.widget.KooVideoView;
import cn.player.media.entity.AdEvent;
import cn.player.media.entity.AdInfo;
import cn.player.media.entity.AdUrls;


public class AdFragment extends BaseFragment {


    private static final int WHAT_COUNT_DOWN = 0;
    private Handler mAdHandler = new AdHandler(this);
    private int mAdTime = 0;

    private FrameLayout flAd;
    private RelativeLayout rlVideoAd;
    private KooVideoView mVideoView;
    private TextView tvCountDown;
    private RelativeLayout rlPhotoAd;
    private ImageView ivPhotoAd;
    private ImageView ivAdClose;

    public boolean isAdCreate;

    private AdUrls adUrls;
    private AdInfo adInfo;
    private Map<Integer, AdEvent> adEvents;
    private String eventUrl;
    private boolean isLiveFlag;
    private int adCatetory;

    private String finalAdUrl;
    // private String finalVideoAdUrl =
    // "http://asp.cntv.lxdns.com/asp/hls/450/0303000a/3/default/8bd71edc25114653a3dd473e172b6bbb/450.m3u8";
    private String finalVideoAdUrl = "http://v.cctv.com/flash/vd/a13d6165468560ed2d73434f9077eacc2c5eb5c33a0b475d03d0736f415d710d/main.m3u8";
    private String finalPhotoAdUrl = "http://p4.img.cctvpic.com/photoAlbum/page/performance/img/2013/10/21/1382356956733_657.jpg";

    // 播放器相关监听器 VideoView暴露
    private OnPreparedListener mOnPreparedListener;
    private OnCompletionListener mOnCompletionListener;
    private OnInfoListener mOnInfoListener;
    private OnErrorListener mOnErrorListener;
    private OnBufferingUpdateListener mOnBufferingUpdateListener;
    private OnVideoSizeChangedListener mOnVideoSizeChangeListener;
    private OnSurfaceListener mOnSurfaceListener;
    private OnVideoClickListener mOnVideoClickListener;

    private OnClickListener mOnClickListener;
    private OnAdListener mAdListener;

//	protected TimeCount mTimeCount;

    private List<AdUrls.Url> videoAdUrls;
    private String videoAdUrl;
    private String photoAdUrl;
    private int adCount;
    public long mCurrentCount;
    private String finalVideoUrl;
    private long currentPosition;
    private boolean isAdStartPlaying;
    /**
     * 判断一段广告是否播放完成
     */
    private boolean isAdPlayCompletion = true;
    private boolean mFlagADAllowed = true;
    private long startRequestTime;
    private long endRequestTime;

    /**
     * 获取AdFragment实例
     *
     * @param adInfo
     * @return
     */
    public static AdFragment newInstance(AdInfo adInfo) {
        AdFragment adFrag = new AdFragment();
        Bundle args = new Bundle();
        args.putSerializable(AdInfo.class.getName(), adInfo);
        adFrag.setArguments(args);
        return adFrag;
    }

    @Override
    protected int setContentLayout() {
        // TODO Auto-generated method stub
        return R.layout.player_ad_layout;
    }

    @Override
    protected void findViews(View rootView) {
        // TODO Auto-generated method stub
        super.findViews(rootView);
        flAd = (FrameLayout) rootView.findViewById(R.id.fl_ad);
        rlVideoAd = (RelativeLayout) rootView.findViewById(R.id.rl_video_ad);
        mVideoView = (KooVideoView) rootView.findViewById(R.id.cmv_surfaceView_ad);
        tvCountDown = (TextView) rootView.findViewById(R.id.tv_count_down);
        rlPhotoAd = (RelativeLayout) rootView.findViewById(R.id.rl_photo_ad);
        ivPhotoAd = (ImageView) rootView.findViewById(R.id.iv_photo_ad);
        ivAdClose = (ImageView) rootView.findViewById(R.id.iv_ad_close);

        setPhotoAdLayout();
        // mVideoView.setZOrderOnTop(true);
        mVideoView.setZOrderMediaOverlay(true);
        mVideoView.setAdPlaying(true);
    }


    private void setPhotoAdLayout() {
        LayoutParams adLayoutParams = rlPhotoAd.getLayoutParams();
        int adWidth = getResources().getDimensionPixelOffset(R.dimen.photo_ad_width);
        int adHeight = getResources().getDimensionPixelOffset(R.dimen.photo_ad_height);
        adLayoutParams.width = Utils.screenWidth(mContext) < 720 ? adWidth : adWidth * 2;
        adLayoutParams.height = Utils.screenWidth(mContext) < 720 ? adHeight : adHeight * 2;
        rlPhotoAd.setLayoutParams(adLayoutParams);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        // LogUtil.i("zl","ADFragment onCreate");
        isAdCreate = true;
        adInfo = (AdInfo) getArguments().getSerializable(AdInfo.class.getName());
        if (adInfo == null) {
            removeSelf();
            if (mAdListener != null) {
                mAdListener.onAdError(adCatetory, getString(R.string.ad_url_null));
                mAdListener.onAdCompletion();
            }
        }
    }

    /**
     * 从缓存获取广告地址数据
     *
     * @return
     */
    private AdUrls getCacheAdUrl() {
        AdUrls adUrls = null;
        try {
            String strAdUrl = SprefUtils.getInstance(mContext).getString(
                    Const.SHAR_PREF_KEY_AD);
            if (!TextUtils.isEmpty(strAdUrl)) {
                adUrls = AdUrls.getAdUrl(new JSONObject(strAdUrl));
            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        return adUrls;
    }

    /**
     * 判断是否所有视频都播放广告
     *
     * @return
     */
    private boolean isAdOver() {
        return Const.AD_MODE_OVER.equals(adInfo.getAdMode());
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onActivityCreated(savedInstanceState);
        // LogUtil.i("zl","ADFragment onActivityCreated");
        adCount = 0;
        if (isAdOver()) {
            doActivityCreated();
        } else {
            adUrls = getCacheAdUrl();
            initJsonData(Const.PRE_AD_URL);
            if (adUrls != null) {
                doActivityCreated();
            }
        }
    }

    private void doActivityCreated() {
        isLiveFlag = (adInfo.getFlag() == Const.LIVE);
        adCatetory = adInfo.getCategory();

        if (adCatetory == Const.AD_PAUSE) {// 图片链接
            if (finalAdUrl == null) {
                photoAdUrl = getReplaceAdUrl(getPhotoAdUrl());
                initJsonData(photoAdUrl);
            } else {
                if (mAdListener != null) {//图片地址不为空，直接展示图片
                    mAdListener.onAdStartPlay(adCatetory);
                }
                rlVideoAd.setVisibility(View.GONE);
                rlPhotoAd.setVisibility(View.VISIBLE);
                finalBitmap.display(ivPhotoAd, finalAdUrl);
                if (mAdListener != null) {
                    mAdListener.onAdPhotoLoadSuccess(null);
                }
            }
        } else {// 视频链接
            videoAdUrls = getVideoAdUrls();
            if (videoAdUrls != null && videoAdUrls.size() > 0
                    && !TextUtils.isEmpty(videoAdUrls.get(adCount).getUrl())) {
                videoAdUrl = getReplaceAdUrl(videoAdUrls.get(adCount++).getUrl());

                //for time calc start
                startRequestTime = System.currentTimeMillis();
                //for time calc end

                initJsonData(videoAdUrl);
            } else {
                removeSelf();
                if (mAdListener != null) {
                    mAdListener.onAdError(adCatetory, getString(R.string.ad_url_null));
                    mAdListener.onAdCompletion();
                }
            }
        }
    }

    @Override
    protected void initDataSuccess(String url, JSONObject response) {
        // TODO Auto-generated method stub
        super.initDataSuccess(url, response);
        if (url.equals(Const.PRE_AD_URL)) {
            if (adUrls == null) {
                adUrls = AdUrls.getAdUrl(response);
                doActivityCreated();
            }
            SprefUtils.getInstance(mContext).putString(Const.SHAR_PREF_KEY_AD, response.toString());
        } else if (url.equals(photoAdUrl)) {

            setAdInfo(response);

            if (finalAdUrl == null || "".equals(finalAdUrl.trim())) {
                removeSelf();
                if (mAdListener != null) {
                    mAdListener.onAdError(adCatetory, getString(R.string.ad_url_null));
                    mAdListener.onAdCompletion();
                }
                return;
            }

            if (mAdListener != null) {//图片地址获取成功，开始展示图片
                mAdListener.onAdStartPlay(adCatetory);
            }
            rlVideoAd.setVisibility(View.GONE);
            rlPhotoAd.setVisibility(View.VISIBLE);
            finalBitmap.configDisplayer(new AdPhotoDisplayer());//广告销毁的时候应恢复默认显示器
            finalBitmap.display(ivPhotoAd, finalAdUrl);
            if (adEvents != null && adEvents.size() > 0 && adEvents.containsKey(1)) {
                eventUrl = adEvents.get(1).getUrl();
                initJsonData(eventUrl);
            }

        } else if (url.equals(videoAdUrl)) {

            //for time calc start
            endRequestTime = System.currentTimeMillis();
            LogUtil.i("zl", "获取广告地址加载时长：" + (endRequestTime - startRequestTime));
            //for time calc end

            setAdInfo(response);
            if (finalAdUrl == null || "".equals(finalAdUrl.trim())) {
                removeSelf();
                if (mAdListener != null) {
                    mAdListener.onAdError(adCatetory, getString(R.string.ad_url_null));
                    mAdListener.onAdCompletion();
                }
                return;
            }
            normalPlay(finalAdUrl);
        }
    }

    /**
     * 自定义广告图片显示器，即图片显示成功和失败时作相应处理，
     *
     * @author zengliang
     */
    class AdPhotoDisplayer implements Displayer {

        @Override
        public void loadCompletedisplay(View arg0, Bitmap arg1,
                                        BitmapDisplayConfig arg2) {
            // TODO Auto-generated method stub
            LogUtil.i("zl", "loadCompletedisplay");
            ivPhotoAd.setImageBitmap(arg1);
            if (mAdListener != null) {
                mAdListener.onAdPhotoLoadSuccess(arg1);
            }
        }

        @Override
        public void loadFailDisplay(View arg0, Bitmap arg1) {
            // TODO Auto-generated method stub
            LogUtil.i("zl", "loadFailDisplay");
            if (mAdListener != null) {
                mAdListener.onAdError(adCatetory, getString(R.string.ad_photo_exception));
                mAdListener.onAdCompletion();
            }
        }

    }

    /**
     * 设置最终广告播放信息
     *
     * @param response
     */
    private void setAdInfo(JSONObject response) {
        try {
            // 取url数据
            adInfo.setUrl(response.optString("url"));
            // 取duration数据
            adInfo.setDuration(response.optString("duration"));
            // 取click数据
            adInfo.setClick(response.optString("click"));

            adEvents = AdEvent.getEvents(response);

            finalAdUrl = adInfo.getUrl();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * 清除广告基本信息，在播放完每一条广告后调用
     */
    private void clearAdInfo() {
        if (adInfo != null) {
            adInfo.setUrl("");
            adInfo.setDuration("");
            adInfo.setClick("");
        }
    }

    @Override
    protected void initDataFailed(String url, int errorNo, String strMsg) {
        // TODO Auto-generated method stub
        super.initDataFailed(url, errorNo, strMsg);
        // for test start

		/*if (adCatetory != Const.AD_PAUSE) {
			Toast.makeText(mContext,"AdFragment:msg = " + strMsg + ",开始播放测试广告...",Toast.LENGTH_SHORT).show();
			rlVideoAd.setVisibility(View.VISIBLE);
			rlPhotoAd.setVisibility(View.GONE);
			normalPlay(finalVideoAdUrl);
		} else {
			Toast.makeText(mContext,"AdFragment:msg = " + strMsg + ",展示测试广告图片...",Toast.LENGTH_SHORT).show();
			rlVideoAd.setVisibility(View.GONE);
			rlPhotoAd.setVisibility(View.VISIBLE);
			finalBitmap.display(ivPhotoAd, finalPhotoAdUrl);
		}*/

        // for test end

        if (!url.equals(eventUrl)) {
            removeSelf();
            if (mAdListener != null) {
                mAdListener.onAdError(adCatetory, strMsg);
                mAdListener.onAdCompletion();
            }
        }

    }

    /**
     * 获取视频广告地址列表
     *
     * @return
     */
    private List<AdUrls.Url> getVideoAdUrls() {
        // TODO Auto-generated method stub

        if (isAdOver()) {
            List<AdUrls.Url> videoAdUrls = new ArrayList<AdUrls.Url>();
            AdUrls adUrls = new AdUrls();
            if (isLiveFlag) {
                videoAdUrls.add(adUrls.new Url(Const.AD_LIVE_CALL_URL1));
                videoAdUrls.add(adUrls.new Url(Const.AD_LIVE_CALL_URL2));
            } else {
                videoAdUrls.add(adUrls.new Url(Const.AD_VOD_CALL_URL1));
                videoAdUrls.add(adUrls.new Url(Const.AD_VOD_CALL_URL2));
            }
            return videoAdUrls;
        }

        if (adUrls == null) {
            return null;
        }
        List<AdUrls.Url> videoAdUrls = null;
        if (isLiveFlag) {
            videoAdUrls = adUrls.getLiveAdCallUrls();
        } else {
            if (adCatetory == Const.AD_CALL) {
                videoAdUrls = adUrls.getVodAdCallUrls();
            } else if (adCatetory == Const.AD_AFTER) {
                videoAdUrls = adUrls.getVodAdAfterUrls();
            }
        }
        return videoAdUrls;
    }

    /**
     * 获取图片广告地址
     *
     * @return
     */
    private String getPhotoAdUrl() {
        if (isAdOver()) {
            return isLiveFlag ? Const.AD_LIVE_PAUSE_URL
                    : Const.AD_VOD_PAUSE_URL;
        }
        if (adUrls == null) {
            return null;
        }
        return isLiveFlag ? adUrls.getLiveAdPauseUrl() : adUrls
                .getVodAdPauseUrl();
    }

    /**
     * 获取替换参数后的广告地址
     *
     * @param adUrl
     * @return
     */
    private String getReplaceAdUrl(String adUrl) {
        String replacedUrl = null;
        try {
            if (isLiveFlag) {
                if (adUrl != null) {
                    replacedUrl = adUrl.replace(Const.PROJECT, adInfo.getAdProject() != null ? adInfo.getAdProject() : Const.PROJECT_)
                            .replace(Const.RANDOM, adInfo.getRandom() != null ? adInfo.getRandom() : Const.RANDOM_)
                            .replace(Const.CHANNEL, adInfo.getChannel() != null ? URLDecoder.decode(adInfo.getChannel(), "UTF-8") : Const.CHANNEL_);
                }
            } else {
                if (adUrl != null) {
                    replacedUrl = adUrl
                            .replace(Const.PROJECT, adInfo.getAdProject() != null ? adInfo.getAdProject() : Const.PROJECT_)
                            .replace(Const.RANDOM, adInfo.getRandom() != null ? adInfo.getRandom() : Const.RANDOM_)
                            .replace(Const.CATALOG, adInfo.getCatalog() != null ? adInfo.getCatalog() : Const.CATALOG_)
                            .replace(Const.VIDEOSETID, adInfo.getVideosetId() != null ? adInfo.getVideosetId() : Const.VIDEOSETID_)
                            .replace(Const.VIDEOID, adInfo.getVideoId() != null ? adInfo.getVideoId() : Const.VIDEOID_)
                            .replace(Const.DURATION, adInfo.getDuration() != null ? adInfo.getDuration() : Const.DURATION_);
                }
            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        return replacedUrl;

    }

    @Override
    protected void setListensers() {
        // TODO Auto-generated method stub
        super.setListensers();
        mOnErrorListener = new OnErrorListener() {

            @Override
            public boolean onError(IMediaPlayer mp, int what, int extra) {
                // TODO Auto-generated method stub
                removeSelf();
                if (mAdListener != null) {
                    mAdListener.onAdError(adCatetory, null);
                    mAdListener.onAdCompletion();
                }
                return true;
            }
        };
        mOnSurfaceListener = new OnSurfaceListener() {

            @Override
            public void onSurfaceCreate() {
                // TODO Auto-generated method stub
                // LogUtil.i("zl","adFragment... onSurfaceCreate");
                if (finalVideoUrl != null) {
                    normalPlay(finalVideoUrl);
                }

            }

            @Override
            public void onSurfaceDestroyed() {
                // TODO Auto-generated method stub
                stopPlayer(false);
                mAdHandler.removeMessages(WHAT_COUNT_DOWN);
            }
        };
        mOnPreparedListener = new OnPreparedListener() {

            @Override
            public void onPrepared(IMediaPlayer mp) {
                // TODO Auto-generated method stub
                LogUtil.e("zl", "ADFragment:MediaPlayer KooVideoView  onPrepared .....");
                mVideoView.start();
            }
        };

        mOnVideoSizeChangeListener = new OnVideoSizeChangedListener() {

            @Override
            public void onVideoSizeChanged(IMediaPlayer mp, int width,
                                           int height, int sar_num, int sar_den) {
                // TODO Auto-generated method stub
                LogUtil.i("zl", "adFragment mVideoView.onVideoSizeChanged()");
                //for time calc start
                long adBufferTime = System.currentTimeMillis();
                LogUtil.i("zl", "广告视频缓冲时长：" + (adBufferTime - endRequestTime));
                LogUtil.i("zl", "广告加载总时长：" + (adBufferTime - startRequestTime));
                //for time calc end

                tvCountDown.setVisibility(View.VISIBLE);
                if (mAdTime == 0 && isAdPlayCompletion) {
                    if (Utils.strToInt(adInfo.getDuration()) != 0) {
                        mAdTime = Utils.strToInt(adInfo.getDuration());
                    } else {
                        adInfo.setDuration(mVideoView.getDuration() + 2000 + "");
                        mAdTime = Utils.strToInt(adInfo.getDuration()) / 1000;
                    }
                }
                if (mFlagADAllowed) {
                    mAdHandler.removeMessages(WHAT_COUNT_DOWN);
                    mAdHandler.sendEmptyMessage(WHAT_COUNT_DOWN);
                } else {
                    mVideoView.pause();
                }

                // 访问服务器确定广告播放开始
                if (adEvents != null && adEvents.size() > 0 && adEvents.containsKey(1)) {
                    eventUrl = adEvents.get(1).getUrl();
                    initJsonData(eventUrl);
                }

                isAdStartPlaying = true;
                isAdPlayCompletion = false;
                if (mAdListener != null) {
                    mAdListener.onAdStartPlay(adCatetory);
                }
            }
        };
        mOnBufferingUpdateListener = new OnBufferingUpdateListener() {

            @Override
            public void onBufferingUpdate(IMediaPlayer mp, int percent) {
                // TODO Auto-generated method stub
                LogUtil.i("zl", "AdFragment onBufferingUpdate percent = " + percent);
            }
        };

        mOnCompletionListener = new OnCompletionListener() {

            @Override
            public void onCompletion(IMediaPlayer mp) {
                // TODO Auto-generated method stub
                isAdStartPlaying = false;
                isAdPlayCompletion = true;
                // 访问服务器确定广告播放完成
                if (adEvents != null && adEvents.size() > 0 && adEvents.containsKey(-1)) {
                    eventUrl = adEvents.get(-1).getUrl();
                    initJsonData(eventUrl);
                }

                clearAdInfo();
                if (adCount < videoAdUrls.size()
                        && !TextUtils.isEmpty(videoAdUrls.get(adCount).getUrl())) {
                    videoAdUrl = getReplaceAdUrl(videoAdUrls.get(adCount++).getUrl());

                    //for time calc start
                    startRequestTime = System.currentTimeMillis();
                    //for time calc end
                    initJsonData(videoAdUrl);
                    mVideoView.stopPlayback();
                    if (mAdListener != null) {
                        mAdListener.onAdSectionCompletion();
                    }
                } else {
                    removeSelf();
                    if (mAdListener != null) {
                        mAdListener.onAdCompletion();
                    }
                }
            }
        };

        mOnClickListener = new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                int id = v.getId();
                if (id == R.id.iv_ad_close) {
                    dettachSelf();
                    if (mAdListener != null) {
                        mAdListener.onAdPhotoClose();
                    }
                } else if (id == R.id.iv_photo_ad) {
                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    intent.setData(Uri.parse(adInfo.getClick()));
                    startActivity(intent);
                }
            }
        };
        mOnVideoClickListener = new OnVideoClickListener() {

            @Override
            public void onVideoClick() {
                // TODO Auto-generated method stub
                if (isAdStartPlaying) {
                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    intent.setData(Uri.parse(adInfo.getClick()));
                    startActivity(intent);
                }
            }
        };

        ivAdClose.setOnClickListener(mOnClickListener);
        ivPhotoAd.setOnClickListener(mOnClickListener);
    }

    /**
     * 正常播放
     *
     * @param path
     */
    private void normalPlay(String path) {
        if (!Utils.isNetConneted(mContext)) {
            if (mAdListener != null) {
                mAdListener.onAdError(adCatetory, getString(R.string.error_net_exception));
                mAdListener.onAdCompletion();
            }
            return;
        }
        finalVideoUrl = path;
        mVideoView.setVideoPath(path);
        if (currentPosition != 0) {
            mVideoView.seekTo(currentPosition);
        }
        // mVideoView.setVideoPath("http://v.cctv.com/flash/vd/a13d6165468560ed2d73434f9077eacc2c5eb5c33a0b475d03d0736f415d710d/main.m3u8");
        // LogUtil.i("zl","AdFragment,normalPlay path = " + path);
        mVideoView.setOnBufferingUpdateListener(mOnBufferingUpdateListener);// 在MediaContrller中已经监听了
        mVideoView.setOnVideoSizeChangedListener(mOnVideoSizeChangeListener);
        mVideoView.setOnPreparedListener(mOnPreparedListener);
        mVideoView.setOnInfoListener(mOnInfoListener);
        mVideoView.setOnCompletionListener(mOnCompletionListener);
        mVideoView.setOnErrorListener(mOnErrorListener);
        mVideoView.setOnSurfaceListener(mOnSurfaceListener);
        mVideoView.setOnVideoClickListener(mOnVideoClickListener);
    }

    /**
     * 播放器释放
     *
     * @param isPlayNew 是否即将播放新视频
     */
    private void stopPlayer(boolean isPlayNew) {
        isAdStartPlaying = false;
        isAdPlayCompletion = true;
        if (isPlayNew) {
            currentPosition = 0;
        } else {
            currentPosition = mVideoView.getCurrentPosition();
            LogUtil.i("zl", "currentPosition= " + currentPosition);
        }
        mVideoView.pause();
        mVideoView.stopPlayback();
    }

    public void removeSelf() {
        if (mVideoView != null) {
            mVideoView.stopPlayback();
        }
        if (getParentFragment() != null) {
            FragmentTransaction mFragTransaction = getParentFragment().getChildFragmentManager().beginTransaction();
            mFragTransaction.remove(this);
            mFragTransaction.commitAllowingStateLoss();
        }
    }

    public void attachSelf() {
        if (getParentFragment() != null) {
            FragmentTransaction mFragTransaction = getParentFragment().getChildFragmentManager().beginTransaction();
//		mFragTransaction.setCustomAnimations(R.anim.base_fade_in,R.anim.base_fade_out);
            mFragTransaction.attach(this);
            mFragTransaction.commit();
        }
    }

    public void dettachSelf() {
        if (getParentFragment() != null) {
            FragmentTransaction mFragTransaction = getParentFragment().getChildFragmentManager().beginTransaction();
//		mFragTransaction.setCustomAnimations(R.anim.base_fade_in,R.anim.base_fade_out);
            mFragTransaction.detach(this);
            mFragTransaction.commit();
        }
    }

    public interface OnAdListener {

        /**
         * 暂停广告图片关闭时调用
         */
        void onAdPhotoClose();

        /**
         * 暂停广告图片加载成功
         *
         * @param bitmap 图片bitmap
         */
        void onAdPhotoLoadSuccess(Bitmap bitmap);

        /**
         * 广告开始播放的时候(包括暂停广告图片开始时)
         *
         * @param adCategory
         */
        void onAdStartPlay(int adCategory);

        /**
         * 非 最后一个贴片广告播放完成时调用
         */
        void onAdSectionCompletion();

        /**
         * 贴片广告全部播放完成时调用
         */
        void onAdCompletion();

        /**
         * 广告错误时调用，会连同onAdCompletion()一同调用
         *
         * @param adCategory
         * @param strMsg
         */
        void onAdError(int adCategory, String strMsg);
    }

    public void setOnAdListener(OnAdListener mOnAdCompletonListener) {
        this.mAdListener = mOnAdCompletonListener;
    }

    /**
     * 获取提示是第几条广告
     *
     * @return
     */
    private String getCountStr() {
        String countStr = null;
        if (videoAdUrls != null && videoAdUrls.size() > 1) {
            countStr = "(" + adCount + "/" + videoAdUrls.size() + ") ";
        }
        return countStr;
    }

    private static class AdHandler extends Handler {
        private WeakReference<Object> mReference;

        public AdHandler(Object loader) {
            mReference = new WeakReference<Object>(loader);
        }

        @Override
        public void handleMessage(Message msg) {
            Object object = mReference.get();
            ((AdFragment) object).handleMessage(msg);
        }
    }

    private void handleMessage(Message msg) {
        switch (msg.what) {
            case WHAT_COUNT_DOWN:
                tvCountDown.setText(/*getCountStr() + */getString(R.string.ad_time_left, mAdTime));
                if (mAdTime != 0) {
                    mAdTime--;
                    mAdHandler.sendEmptyMessageDelayed(WHAT_COUNT_DOWN, 1000);
                } else {
                    tvCountDown.setVisibility(View.GONE);
                    if (!isAdPlayCompletion && mAdListener != null) {//广告卡住时，如果时间到了，直接销毁广告
                        removeSelf();
                        mAdListener.onAdCompletion();
                    }
                }
                break;

            default:
                break;
        }
    }

    /**
     * 当AdFragment销毁时清除图片广告的内存缓存
     * 以满足下次创建时不从内存中获取，从sd卡或者网络获取，
     * 从而达到展示图片的时候能够执行Displayer中的loadCompletedisplay()方法
     * <p/>
     * 销毁时就恢复默认的显示器
     */
    public void clearAdPhotoCache() {
        if (!TextUtils.isEmpty(finalAdUrl)) {
            finalBitmap.clearMemoryCache(finalAdUrl);
        }
        finalBitmap.configDisplayer(new SimpleDisplayer());//恢复默认的显示器
    }


    @Override
    public void onAttach(Activity activity) {
        // TODO Auto-generated method stub
        super.onAttach(activity);
        // LogUtil.i("zl","ADFragment onAttach");
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        // LogUtil.i("zl","ADFragment onCreateView");
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    @Override
    public void onStart() {
        // TODO Auto-generated method stub
        super.onStart();
        // LogUtil.i("zl","ADFragment onStart");
    }

    @Override
    public void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        if (null != mVideoView && !mVideoView.isPlaying()) {
            mVideoView.start();
            mFlagADAllowed = true;
        }
        if (!isAdPlayCompletion) {
            mAdHandler.sendEmptyMessage(WHAT_COUNT_DOWN);
        }
        LogUtil.i("zl", "ADFragment onResume");
    }

    @Override
    public void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        if (null != mVideoView && mVideoView.isPlaying()) {
            mVideoView.pause();
            mFlagADAllowed = false;
        }
        mAdHandler.removeMessages(WHAT_COUNT_DOWN);
        LogUtil.i("zl", "ADFragment onPause");
    }

    @Override
    public void onStop() {
        // TODO Auto-generated method stub
        super.onStop();
        // LogUtil.i("zl","ADFragment onStop");
    }

    @Override
    public void onDestroyView() {
        // TODO Auto-generated method stub
        super.onDestroyView();
        //LogUtil.i("zl","ADFragment onDestroyView");
        mAdHandler.removeMessages(WHAT_COUNT_DOWN);
    }

    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        // LogUtil.i("zl","ADFragment onDestroy");
        isAdCreate = false;
    }

    @Override
    public void onDetach() {
        // TODO Auto-generated method stub
        super.onDetach();
        // LogUtil.i("zl","ADFragment onDetach");
        clearAdPhotoCache();
    }
}
